package com.fpost.test;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

import com.fpost.dao.impl.ArticleDAO;
import com.fpost.domain.Article;
import com.fpost.domain.ArticleVersion;
import com.fpost.domain.User;
import com.fpost.manager.ArticleManager;
import com.fpost.manager.UserManager;

public class ArticleGenerator {
	
	private static List<String> listOfWords = DictionaryUtil.getDictionary();

	public static void main(String[] args) {
		
		for (int i = 1; i < 12; i++) {
			new ArticleManager().saveArticles(generateArticles(1000, i, "User1"));
			System.out.println("Done " + i);
		}
		System.out.println("Done!");
		//readArticles();

	}

	private static void readArticles() {
		List<Article> articles = null;
		User user = new UserManager().getByUsername("User2");
		// articles = new ArticleDAO().getByUserId(user.getUserId());
		articles = new ArticleDAO().getCurrentArticlesByUser(user);

		for (Article article : articles) {
			article.printDetails();
		}
	}

	private static List<Article> generateArticles(int number, int type, String username) {
		
		List<Article> articleList = new ArrayList<Article>();
		Random random = new Random();
		User user = new UserManager().getByUsername(username);

		for (int i = 0; i < number; i++) {
			ArticleVersion version = new ArticleVersion();
			version.setArticleTypeId(type);
			version.setTitle(getSomeWords(random.nextInt(10)+1));
			
			String body = getSomeWords(250*10);
			String[] bodyArray = body.trim().split(" ");
			StringBuilder sb = new StringBuilder();
			for (int j = 0; j < 20; j++) {
				sb.append(bodyArray[j]);
				sb.append(" ");
			}
			version.setSummary(sb.toString().trim());
			version.setBody(body);
			
			version.setCreatedOn(new Date());
			version.setCreatedIp("127.0.0.1");

			Article article = new Article();
			article.setUser(user);
			article.getVersions().add(version);

			articleList.add(article);
		}
		return articleList;
	}
	
	private static String getSomeWords(int numberOfWords) {
		StringBuilder sb = new StringBuilder();
		Random r = new Random();
		for (int i = 0; i < numberOfWords; i++) {
			//sb.append(generateRandomWord(r.nextInt(15)+1)).append(" ");
			sb.append(getRandomWord()).append(" ");
			//System.out.println(i);
		}
		return sb.toString();
	}
	
	private static String getRandomWord() {
		Random random = new Random();
		return listOfWords.get(random.nextInt(listOfWords.size()));
	}
	
	@Deprecated
	private static String generateRandomWord(int wordLength) {
	    Random r = new Random(); 
	    StringBuilder sb = new StringBuilder(wordLength);
	    for(int i = 0; i < wordLength; i++) {
	        char tmp = (char) ('a' + r.nextInt('z' - 'a'));
	        sb.append(tmp);
	    }
	    return sb.toString();
	}

}
